using Microsoft.AspNetCore.Components.Authorization;
using MyBlogServer.Models;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace MyBlogServer.Services
{
    public class CustomAuthenticationStateProvider : AuthenticationStateProvider
    {
        private readonly UserService _userService;
        private readonly IJwtAuthService _jwtAuthService;
        private ClaimsPrincipal _currentUser = new ClaimsPrincipal(new ClaimsIdentity());
        
        public CustomAuthenticationStateProvider(UserService userService, IJwtAuthService jwtAuthService)
        {
            _userService = userService;
            _jwtAuthService = jwtAuthService;
        }
        
        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            try
            {
                // 检查是否有有效的JWT Token
                var token = await _jwtAuthService.GetStoredTokenAsync();
                if (!string.IsNullOrEmpty(token) && await _jwtAuthService.IsTokenValidAsync())
                {
                    var username = await _jwtAuthService.GetUsernameFromTokenAsync(token);
                    if (!string.IsNullOrEmpty(username))
                    {
                        var claims = new[] { new Claim(ClaimTypes.Name, username) };
                        var identity = new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme);
                        _currentUser = new ClaimsPrincipal(identity);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取认证状态时发生错误: {ex.Message}");
            }
            
            // Return the current user state
            Console.WriteLine($"获取当前认证状态: {_currentUser?.Identity?.IsAuthenticated}, 用户: {_currentUser?.Identity?.Name}");
            return new AuthenticationState(_currentUser ?? new ClaimsPrincipal(new ClaimsIdentity()));
        }
        
        public void NotifyUserLoggedIn(string username)
        {
            Console.WriteLine($"设置用户登录状态: {username}");
            var claims = new[] { new Claim(ClaimTypes.Name, username) };
            // 使用JWT认证类型，与Program.cs中配置的方案名称一致
            var identity = new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme);
            _currentUser = new ClaimsPrincipal(identity);
            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
            Console.WriteLine($"认证状态已更新: {_currentUser?.Identity?.IsAuthenticated}, 用户: {_currentUser?.Identity?.Name}");
        }
        
        public void NotifyUserLoggedOut()
        {
            Console.WriteLine("用户登出");
            var identity = new ClaimsIdentity();
            _currentUser = new ClaimsPrincipal(identity);
            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
            Console.WriteLine("认证状态已清除");
        }
    }
}